import { Component, OnInit } from '@angular/core';
import { Http } from "@angular/http";
import { MeiyuDataSource } from "../datasource/meiyu-data-source";
import { DatePipe } from '@angular/common';
import { environment } from '../../../../environments/environment';
import { CommentEditComponent } from '../../dialog/comment-edit/comment-edit.component';
import {MdDialog} from '@angular/material';

@Component({
  selector: 'app-city',
  templateUrl: './city.component.html',
  styleUrls: ['./city.component.scss']
})

export class CityComponent implements OnInit {
  busy : any;
  source : MeiyuDataSource;
  settings = {
    pager: {
      perPage: 10
    },
    actions: {
      edit: false,
      delete: false,
      add: false,
      columnTitle: '操作',
      custom: [
        { name: 'view', title: `<i class="fa fa-eye fa-2x"></i> ` },
        { name: 'delete', title: `<i class="fa fa-remove fa-2x"></i> ` },
        { name: 'edit', title: `<i class="fa fa-edit fa-2x"></i> ` },
      ],
      position: 'right',
    },
    attr: {
      class: 'table table-hover table-striped'
    },
    hideSubHeader: true,
    noDataMessage: '',
    columns: {
      id: {
        title: '编号',
      },
      cityName: {
        title: '城市',
        width: '20%',
      },
      createdAt: {
        title: '抓取时间',
        valuePrepareFunction: (timestamp) => {
          var raw = new Date(timestamp);
          return this.datePipe.transform(raw, 'dd MMM yyyy');
        }
      },
    }
  };

  constructor(private http: Http, 
    private dialog: MdDialog,
    private datePipe: DatePipe) { 

    this.source = new MeiyuDataSource(http, {
      endPoint: environment.endPoint + '/cities',
      totalKey: 'totalElements',
      dataKey: 'content',
      pagerPageKey: 'page',
      pagerLimitKey: 'size',
      sortFieldKey: 'sort',
    })
    this.source.loading().subscribe(promise => {
      this.busy = promise;
    })
  }

  ngOnInit() {
  }
  onSearch(keyword) {
    console.log('search keyword : %s', keyword);
    this.source.setFilter([
      { field: 'cityName', search: keyword },
    ], false);
  }

  onCustom(action, event) {
    console.log('action : %s ', action);
    console.log(event);
  }

  onUserChoice(event) {
    console.log(event);
    
    if(event.action == 'view') {
      this.dialog.open(CommentEditComponent, {
        height: '400px',
        width: '600px',
      })
    }
  }

}
